import { connect } from 'dva'
import { useEffect, useState } from 'react'

import { getEntrancesListByTypeApi } from '@/api/app'
import PageLayout from '@/components/PageLayout'
import { getBasicFn } from '@/utils/dvaUtil/index'
import { requestWithTry } from '@/utils/request'
import { hasProtocol } from '@/utils/urlUtil'

import ICON_SYSTEM_HOME from './imgs/icon_system_home.png'
import styles from './index.module.less'

const { toAction } = getBasicFn({ namespace: 'app' })

/**
 * @param {{ app: import('@/models/app').state}} param0
 * @returns
 */
const Home = ({ app }) => {
  const { currentEntranceId } = app
  const [list, setList] = useState([])

  const getList = async () => {
    const { data } = await requestWithTry(getEntrancesListByTypeApi)
    setList(data.filter(it => it.entranceName !== '集成平台'))
  }

  useEffect(() => {
    getList()
  }, [])

  const onClick = async entranceId => {
    if (currentEntranceId === entranceId) return
    await toAction('changeEntrance', { entranceId })
  }

  return (
    <PageLayout className={styles.home}>
      <div className={styles.wrapper} style={{ justifyContent: list.length > 2 ? 'space-between' : 'start' }}>
        {list.map(item => {
          let Tag = 'div'
          const tagProps = {
            className: `${styles.entrance} ${currentEntranceId === item.entranceId ? styles.entranceCurrent : ''}`,
          }
          if (item.type === 2) {
            let url = item.externalUrl
            if (url && !hasProtocol(url)) {
              url = `//${url}`
            }
            Tag = 'a'
            Object.assign(tagProps, {
              href: url,
              target: '_blank',
              style: !url ? { pointerEvents: 'none', cursor: 'not-allowed' } : undefined,
              title: !url ? '暂无可访问链接' : undefined,
            })
          } else {
            Object.assign(tagProps, {
              onClick: () => onClick(item.entranceId),
            })
          }
          return (
            <Tag key={item.entranceId || item.externalUrl} {...tagProps}>
              <p>
                <img src={item.icon || ICON_SYSTEM_HOME} alt={item.entranceName} width={44} height={44} />
              </p>
              <div className={styles.entranceName}>{item.entranceName}</div>
              <p className={styles.description}>{item.description}</p>
            </Tag>
          )
        })}
      </div>
    </PageLayout>
  )
}

export default connect(({ app }) => ({
  app,
}))(Home)
